<template>
    <div class="flex bg-[#eee] p-[5px] h-[83vh] w-[83vw]">
        <div class="bg-[#FFF] w-[53vw] h-[79vh] mr-[5px] text-sm p-[5px] overflow-auto soll">
            <div class="title">
                <label>新闻内容</label>
                <input type="text" v-model="searchText" placeholder="请输入搜索内容" />
            </div>
            <div class="type">
                <span class="">新闻类型：</span>
                <Categroy v-model="filterModel.classReal" title="新闻类型" :catlist="newsType"></Categroy>
            </div>

            <div class="type">
                <span>筛选条件：</span>
                <div class="mt-[5px]">
                    <Filter v-model="filterModel.filter"></Filter>
                </div>
            </div>
            <hr />

            <div class="items-center">
                <div class="py-[1vh] border-dashed border-[1px] text-center mt-[2vh] mb-[1vh] rounded-md" @click="handleCreate" v-permission="['write']">
                    <el-icon class="pt-[0.2vh] mr-[1vw]">
                        <Plus />
                    </el-icon>手动添加新闻
                </div>
                <NewsItem v-for="item in newsList" :key="item.id" :data="item" @addData="handleAdd"
                    @removeData="handleRemove" @click="handleNewsClick" @edit="handleEdit" />
            </div>

            <el-pagination v-model:page-size="currentSize" v-model:current-page="current"
                layout="prev, pager, next,total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :total="total" />
        </div>

        <div class="flex-1 bg-[#fff] h-[79vh] overflow-auto soll">
            <ReleaseList ref="releaseRef" />
        </div>

        <el-drawer v-model="drawer" title="I am the title" :with-header="false" size="60%"  destroy-on-close>
            <NewsDetail :mode="mode" @close="drawer=false" :data="selectedNewsData" />
        </el-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, useTemplateRef } from 'vue'
import { getNewsPool, updateNews } from '@/api/newsApi'
import Categroy from '@/components/Categroy.vue'
import Filter from '@/components/Filter.vue'
import NewsItem from '@/components/NewsItem.vue'
import ReleaseList from '@/components/ReleaseList.vue'

import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import NewsDetail from '@/components/NewsDetail.vue'

// import Editor from '@/components/Editor.vue'

interface NewsItem {
    id: number;
    newsTitle: string;
    abstractReal: string;
    siteName: string;
    createTime: string;
    isPublished: boolean;
    pubTime?: string;
    addMode: number;
    classReal: number;
    classModel: string;
    isSelect: number;
    newsSource: string;
    newsTime: string;
    opPerson: string;
}
const searchText = ref('')
const currentSize = ref(10)
let current = ref(1)
const newsList = ref()
const total = ref<number | string | undefined>(0)
const releaseRef = useTemplateRef<{ releaseList: [], refersh: () => void }>('releaseRef')
const mode = ref<'read' | 'create' | 'edit'>('read')
const drawer = ref(false)
const selectedNewsData = ref()

const newsType = [
    { value: -1, label: '全部' },
    { value: 1, label: '宏观环境' },
    { value: 2, label: '行业趋势' },
    { value: 3, label: '供应链动态' },
    { value: 4, label: '国际能源' },
    { value: 5, label: '其他' }
]

const filterModel = reactive({
    keywords: '',
    classReal: 0,
    filter: {
        addMode: null,
        isPublished: null,
        timeRange: null,
        sortby: null,
    }
})

const handleCreate=()=>{
    drawer.value = true
    mode.value = 'create'
}

//加入待发布
const handleAdd = async (id: number) => {
    if ((releaseRef.value?.releaseList as []).length >= 10) {
        ElMessage.warning('已达到添加上限，请先移除再添加！')
    }
    const res = await updateNews({ id, isSelect: 1 })
    if (res.code === 200) {
        ElMessage.success('添加成功')
        newsList.value = newsList.value.map((it: NewsItem) => {
            if (it.id === id) {
                it.isSelect = 1
            }
            return it;
        })
    }
}
//移除
const handleRemove = async (id: number) => {
    const res = await updateNews({ id, isSelect: 0 })
    if (res.code == 200) {
        ElMessage.success('移除成功')
        newsList.value = newsList.value.map((it: NewsItem) => {
            if (it.id === id) {
                it.isSelect = 1
            }
            return it;
        })
    }
}

const handleEdit = (newsData: unknown) => {
    drawer.value = true
    mode.value = 'edit'
    selectedNewsData.value = newsData
}

const handleNewsClick = (newsData:unknown) => {
    drawer.value = true
    mode.value = 'read'
    selectedNewsData.value = newsData
}

watch([filterModel, currentSize, current], (n) => {
    const { filter, ...rest } = n[0]
    let filterParams = {
        currentSize: n[1],
        current: n[2],
        ...rest,
        ...filter
    }
    const finalParams = Object.entries(filterParams).reduce((prev, [key, value]) => {
        if (typeof value === 'string' && value || typeof value === 'number' && value >= 0 || Array.isArray(value)) {

            if (key == 'timeRange ') {
                const [createTimeFrom, createTimeTo] = value as unknown as [string, string];
                return {
                    ...prev,
                    createTimeFrom,
                    createTimeTo
                }
            }
            return {
                ...prev,
                [key]: value
            }
        }
        return prev
    }, {})
    const usp = new URLSearchParams(finalParams as unknown as Record<string, string>);
    getNewsPool(usp.toString()).then(res => {
        newsList.value = res.data?.records
        total.value = res.data?.total
    })
})

const handleSizeChange = (n: any) => {
    currentSize.value = n
    current.value = 1
    const usp = new URLSearchParams({
        pageSize: currentSize.value.toString(),
        current: current.value.toString(),
    })
    getNewsPool(usp.toString()).then(res => {  
        console.log(res.data)
        newsList.value = res.data?.records
        total.value = res.data?.total
    })
}
const handleCurrentChange = (n: any) => {
    current.value = n
    const usp = new URLSearchParams({
        pageSize: currentSize.value.toString(),
        current: current.value.toString(),
    })
    getNewsPool(usp.toString()).then(res => {
        newsList.value = res.data?.records
        total.value = res.data?.total
    })
}
</script>

<style scoped>
.type {
    display: flex;
}

.type>span {
    display: inline-block;
    align-items: center;
    margin-right: 10px;
    height: 56px;
    line-height: 56px;
}

p {
    display: inline-block;
}

input {
    width: 200px;
    height: 30px;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding-left: 10px;
    margin-left: 20px;
}

.title {
    display: flex;
    align-items: center;
}

.soll::-webkit-scrollbar {
    display: none;
}

.empty-state {
    text-align: center;
    padding: 50px 0;
    color: #999;
}
</style>